/**
 * Copyright (c) 2016-2020 https://github.com/zhaohuatai
 *
 * contact z_huatai@qq.com
 *  
 */
package org.zfes.snowy.core.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;

public class IPUtil {
	 public static long getClientLongIp(HttpServletRequest request) {
		 String ipaddress=getClientIpAddr( request);
		 return ipStrToLong( ipaddress);
	 }
	 
	 
    public static String getClientIpAddr(HttpServletRequest request) {
    	 String ip ="";
        if (request == null) {
        	ip= "unknown";
        }
        ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("HTTP_CLIENT_IP");  
        } 
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if(ip != null && ip.length() > 15){    
            if(ip.indexOf(",")>0){     
                ip = ip.substring(0,ip.indexOf(","));     
            }     
        }  
        if(ZStrUtil.hasNoText(ip)||"unknown".equalsIgnoreCase(ip)) {
        	ip="unknown";
        }
        if("0:0:0:0:0:0:0:1".equals(ip)) {
        	return "127.0.0.1";
        }
        return ip;
    }
    
    public static String getLocalIPAddress() {
        InetAddress inet = null;
        try {
            inet = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
        	return "unknown";
           // e.printStackTrace();
        }
        return inet.getHostAddress();
    }
    
    
    public static long ipStrToLong(String ipaddress) { 
    	if(ZStrUtil.hasNoText(ipaddress)||"unknown".equalsIgnoreCase(ipaddress)) {
    		return -1L;
    	}
        long[] ip = new long[4];  
        int i = 0;  
        for(String ipStr : ipaddress.split("\\.")){  
            ip[i] = Long.parseLong(ipStr);  
            i++;  
        }    
        return (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3];    
    } 
    public static void main(String[] sd){
    	 System.out.println(ipStrToLong("127.0.0.1"));
		 System.out.println(iplongToIp(99L));
	 }
    public static String iplongToIp(long ipaddress) {    
        StringBuffer sb = new StringBuffer("");  
        sb.append(String.valueOf((ipaddress >>> 24)));  
        sb.append(".");  
        sb.append(String.valueOf((ipaddress & 0x00FFFFFF) >>> 16));  
        sb.append(".");  
        sb.append(String.valueOf((ipaddress & 0x0000FFFF) >>> 8));  
        sb.append(".");  
        sb.append(String.valueOf((ipaddress & 0x000000FF)));  
        return sb.toString();  
    }  
    public static String iplongToIp(Long ipaddr) { 
    	if(ipaddr==null){
    		return "";
    	}
        long y = ipaddr % 256; 
        long m = (ipaddr - y) / (256 * 256 * 256); 
        long n = (ipaddr - 256 * 256 *256 * m - y) / (256 * 256); 
        long x = (ipaddr - 256 * 256 *256 * m - 256 * 256 *n - y) / 256; 
        return m + "." + n + "." + x + "." + y; 
    } 
    
    public static String getMACAddress(InetAddress ia){    
        //获得网络接口对象（即网卡），并得到mac地址，mac地址存在于一个byte数组中。    
        byte[] mac=null;
		try {
			mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
		} catch (SocketException e) {
			return "";
		}    
        //下面代码是把mac地址拼装成String    
        StringBuffer sb = new StringBuffer();    
            
        for(int i=0;i<mac.length;i++){    
            if(i!=0){    
                sb.append("-");    
            }    
            //mac[i] & 0xFF 是为了把byte转化为正整数    
            String s = Integer.toHexString(mac[i] & 0xFF);    
            sb.append(s.length()==1?0+s:s);    
        }    
            
        //把字符串所有小写字母改为大写成为正规的mac地址并返回    
        return sb.toString().toUpperCase();    
    }
}
